package com.yss.script;

import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.AviatorEvaluatorInstance;
import com.googlecode.aviator.Expression;
import lombok.Getter;

import java.util.Collection;

public class ScriptManager {

    @Getter
    private final static AviatorEvaluatorInstance aviatorInstance;

    static {
        aviatorInstance = AviatorEvaluator.getInstance();
    }

    public Object compileAndExecute(String script, Object params) {
        return this.execute(compile(script), params);
    }

    public Expression compile(String script) {
        return aviatorInstance.compile(script, true);
    }

    public Object execute(Expression expression, Object params) {
        try {
            return expression.execute(expression.newEnv("$", params));
        } catch (Exception e) {
            return false;
        }
    }

    public void invalidateCache(Collection<String> scripts) {
        scripts.forEach(script -> invalidateCache(script));
    }

    public void invalidateCache(String script) {
        aviatorInstance.invalidateCache(script);
    }

}
